package com.gurumades.jsonform.client.forms;

import java.util.HashMap;

import com.google.gwt.dom.client.DivElement;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.gurumades.jsonform.client.JSONUtils;

public abstract class FormItemViewAbstract extends Composite implements
		FormItemViewIF {

	@UiField
	Label label;
	@UiField
	FocusWidget value;
	@UiField
	DivElement description;

	String[] allowedValues;
	String[] allowedValuesLabels;

	JSONObject itemSettings;

	protected String fieldID;

	HashMap<String, String> extras = new HashMap<String, String>();

	public void setFieldID(String fieldID) {
		this.fieldID = fieldID;
	}

	public String getFieldID() {
		return fieldID;
	}

	@Override
	public void initFormItem(JSONValue value, JSONObject formItemSettings) {
		this.itemSettings = formItemSettings;

		String allowed = JSONUtils.getString("allowedValues", formItemSettings);

		if (allowed != null) {
			allowedValues = allowed.split(";");
			allowedValuesLabels = new String[allowedValues.length];
			for (int i = 0; i < allowedValues.length; i++) {
				String[] keyValue = allowedValues[i].split("=");
				if (keyValue.length == 2) {
					allowedValuesLabels[i] = keyValue[0].trim();
					allowedValues[i] = keyValue[1].trim();
				}else{
					allowedValues[i] = allowedValuesLabels[i] = allowedValues[i].trim();
				}
			}
		}

		JSONObject extra = formItemSettings.get("extra").isObject();
		if (extra != null
				&& extra.get("extraKeyAndExtraValue").isArray() != null) {
			JSONArray arr = extra.get("extraKeyAndExtraValue").isArray();

			for (int i = 0; i < arr.size(); i = i + 2) {
				JSONObject key = arr.get(i).isObject().get("JAXBElement").isObject();
				JSONObject val = arr.get(i+1).isObject().get("JAXBElement").isObject();
				extras.put(JSONUtils.getString("value", key),
						JSONUtils.getString("value", val));
			}

		}

		setFieldID(JSONUtils.getString("id", formItemSettings));

		label.setText(JSONUtils.getString("label", formItemSettings));
		description.setInnerHTML(JSONUtils
				.getString("description", formItemSettings));
		
		String label = JSONUtils.getString("label", formItemSettings);
		
		if (label == null) {
			label = JSONUtils.getString("name", formItemSettings);
		}
		
		this.label.setText(label);
	}
	
	@Override
	public void setError(boolean b, String string) {
		if (b) {
			addStyleName("jsonForm-error");
		}else{
			removeStyleName("jsonForm-error");
		}
	}
}
